package com.onec.service.netty.coder;

import cn.hutool.core.util.RandomUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

public class NettyOpenBoxDecoder {

    static String spliter = "/r/n";
    static String content = "疯狂创客高性能学习";


    @Test
    public void testLineBasedFrameDecoder() throws UnsupportedEncodingException {
        ChannelInitializer i = new ChannelInitializer<EmbeddedChannel>() {
            @Override
            protected void initChannel(EmbeddedChannel ch) throws Exception {
                ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                ch.pipeline().addLast(new StringDecoder());
                //ch.pipeline().addLast(new stringproc)

            }
        };
        EmbeddedChannel embeddedChannel = new EmbeddedChannel(i);
        for (int j = 0; j < 100; j++) {
            int random = RandomUtil.randomInt(3);
            ByteBuf byteBuf = Unpooled.buffer();
            for (int k = 0; k < random; k++) {
                byteBuf.writeBytes(content.getBytes(StandardCharsets.UTF_8));
            }

            byteBuf.writeBytes(spliter.getBytes(StandardCharsets.UTF_8));
            embeddedChannel.writeInbound(byteBuf);
        }


    }


}
